// pages/transportConfirm/index.js
import requestUtil from '../../../baseRequest.js'
import requestUrls from '../../../requestUrl.js'
import { $Message } from '../../../components/base/index'
import commonUtils from '../../../utils/util.js'

let openid = wx.getStorageSync('openid')
let formTempObject = {}
const uploadUrlCommons = '/api/insurance/image/upload'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    openid: openid,
    transportConfirm: {},
    isUnloadGoodsPhoto: false,
    signKey: 'receiverSignature',
    unloadGoodsPhoto: {
      itemType: 'uploader',
      title: '卸货照片',
      name: 'unloadedPictures',
      files: [],
      count: 30,
      uploadUrl: requestUrls.baseUrl + uploadUrlCommons,
      isUpload: false,
      uploadComplete: 'completeUnloadedPictures',
      attentionText: '卸货照片最多上传30张图片',
      sourceType: 'camera', //'all/camera'
      //是否提交过
      isSubmit: false
    }
  },
  completeUnloadedPictures(e) {
    console.log("获取信息回调", e)
    let detail = e.detail
    let status = detail.status
    if (status || status == 'error') {
      console.log("卸货照片上传失败，请重新选择上传")
      this.showErrorMessage("卸货照片上传失败，请重新选择上传");
      this.setData({
        showSpin: false,
        ['formParam.unloadedPictures']: [],
        ['unloadGoodsPhoto.isUpload']: false,
      })
      return
    }
    this.setData({
      ['formParam.unloadedPictures']: detail
    })
    this.saveComplete();
  },
  /**获取救援司机信息 */
  getDetail() {
    if (!this.data.openid) {
      this.setData({
        openid: wx.getStorageSync('openid')
      })
    }
    //原逻辑
    // if (this.data.confirmId==='' || this.data.confirmId === null || this.data.confirmId === undefined) {
      let param = {
        'openid': this.data.openid,
        'id': this.data.confirmId? this.data.confirmId:this.data.id
      }
      let url = requestUrls.transportConfirm.load
      requestUtil.postRequest(url, param, (res) => {
        console.log('收货确认单查询结果');
        console.log(res);
        let info = res
        this.setData({
          transportConfirm: info,
          goodsPhotos: info.goodsPhotos
        })
      }, () => { })
    // } else {
    //   //如果传入数据不为空，则查询数据库，获取自动生成的运输确认单信息
    //   const formData = {
    //     openId: this.data.openid,
    //     criteria: {
    //       id: this.data.truckOrderId
    //     }
    //   };
    //   requestUtil.postRequest(requestUrls.truckOrder.getById, formData, (res) => {
    //     this.setData({
    //       transportConfirm: res.result.transportConfirmForm,
    //       id: res.result.transportConfirmForm.id,
    //       editable: true,
    //     })
    //   })
    // }

  },
  onTypeChange(e) {
    this.setData({
      authType: parseInt(e.detail.value)
    })
  },
  handleChange({ detail = {} }) {
    console.log('handleChange', detail)
    formTempObject[detail.key] = detail.value
  },
  /**完成*/
  saveComplete() {
    let param = this.data.formParam
    let url = requestUrls.transportConfirm.complete

    console.log('param', param, 'url', url)
    // let unloadedPictures = param.unloadedPictures;
    // if (unloadedPictures || unloadedPictures.length > 0) {

    //   let unloadedPictureList = unloadedPictures.map((item, index, arr) => {
    //     return item.url;
    //   });
    //   param.unloadedPictures = unloadedPictureList;

    // }
    param.id = this.data.id
    param.openid = this.data.openid
    requestUtil.postRequest(url, param, (res) => {
      console.log(res)
      this.setData({
        showSpin: false
      })
      if (res.code == 10012) {
        this.setData({
          isSubmit: true
        })
        wx.showModal({
          title: '提交失败',
          content: res.message,
          showCancel: false,
          success: res => { }
        })
        return
      }
      //进入第二步，填写接货确认单
      wx.redirectTo({
        url: '../detail/index?id=' + res.id
      })
    }, () => { })
  },

  /**提交表单信息 */
  submitForm(event) {
    let data = event.detail.value;
    const optType = event.detail.target.dataset.opt;
    if (optType && optType === 'complete') {
      if (this.checkFormData(event.detail.value)) {
        if (this.data.isSubmit) {
          this.setData({
            showSpin: true,
            formParam: data,
          })
          this.saveComplete()
        } else {
          this.setData({
            showSpin: true,
            ['unloadGoodsPhoto.isUpload']: true,
            formParam: data,
          })
        }
        // 返回顶部
        wx.pageScrollTo({
          scrollTop: 0,
        })
      }
    } else if (optType === 'complain') {
      //跳转到仲裁单创建页面
      wx.navigateTo({
        url: '/pages/arbitration/create/index?publishSide=' + this.data.publishSide + "&transportConfirmFormId=" + this.data.id
      });
    }

  },

  /**检查表单信息 */
  checkFormData(data) {
    // return false
    if (!data.unloadPlace || commonUtils.trim(data.unloadPlace) == 0) {
      this.showErrorMessage('卸货地址不能为空')
      return false
    }
    if (commonUtils.isEmoji(data.unloadPlace)) {
      this.showErrorMessage('卸货地址不能包含表情字符')
      return false
    }
    return true
  },


  /**显示错误信息 */
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { id = '', confirmId = '' } = options;
    console.log('收货确认单传入数据');
    console.log(options);
    this.setData({
      id: confirmId?confirmId:id,
      confirmId: confirmId
    })
    //获取司机初始化数据
    this.getDetail()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      signPaths: getApp().globalData.signTempPath,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    getApp().cleanSignTempPathCache()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // }
})
